/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.transas.zorlog.data;

import com.transas.zorlog.data.log.Field;
import com.transas.zorlog.data.log.PacketAdapter;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author amalikov
 *
 * "Convert on the fly" implementation of DataSource interface.
 */
public class DataSourcePacketized extends DataSource {
    public DataSourcePacketized() {
		table = new ArrayList<>();
    }

	@Override
    public Object getHandle(String name) {
		return findField(name);
    }

	@Override
	public double getValue(Object handle, int index) {
		final FieldAddr fa = (FieldAddr)handle;
		return fa != null ? table.get(index).get(fa.group).getValue(fa.field) : 0;
	}	

	@Override
	public String getValueAsString(Object handle, int index, NumberFormat nf) {
		final FieldAddr fa = (FieldAddr)handle;
		return fa != null ? table.get(index).get(fa.group).getValueAsString(fa.field, nf) : "";
	}
	
	@Override
	public double[] getValues(String name) {
		final FieldAddr fa = (FieldAddr)getHandle(name);
		if (fa == null)
			return new double[0];
		
		double[] res = new double[table.size()];
		for (int i = 0; i < res.length; ++i)
			res[i] = table.get(i).get(fa.group).getValue(fa.field);
		return res;
	}	
	
	@Override
	public int getSize() {
		return table.size();
	}
	
	@Override
    public List<String> getNames() {
		List<String> names = new ArrayList<>();
		
		if (!table.isEmpty()) {
			List<PacketAdapter> packetAdapters = table.get(0);
			for (PacketAdapter packetAdapter : packetAdapters) {
				List<Field> fields = packetAdapter.getFields();
				for (Field field : fields) {
					names.add(field.name);
				}
			}
		}
		
        return names;
    }
	
	@Override
	public String getAttribute(Object handle, String attrName) {
		final FieldAddr fa = (FieldAddr)handle;
		if (fa != null) {
			return table.get(0).get(fa.group).getFields().get(fa.field).getAttribute(attrName);
		} else
			return "";
	}		

	public void addRow(List<PacketAdapter> row) {
		table.add(row);
	}

	private FieldAddr findField(String name) {
		if (!table.isEmpty()) {
			int g = 0;
			
			List<PacketAdapter> packetAdapters = table.get(0);
			for (PacketAdapter packetAdapter : packetAdapters) {
				List<Field> fields = packetAdapter.getFields();

				int f = 0;			
				for (Field field : fields) {
					if (field.name.equals(name))
						return new FieldAddr(g, f);
					++f;
				}
		
				++g;
			}
		}
		
		return null;
	}

	private class FieldAddr {
		FieldAddr(int g, int f) {
			group = g;
			field = f;
		}
		
		int group = 0;
		int field = 0;
	}
	
    private List<List<PacketAdapter>> table;
}


